package ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.security.impl;

import ace.cmp.util.CaseFormatUtils;
import java.util.function.Function;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

/**
 * 安全管理工具.
 *
 * @author caspar
 */
public class SecurityManagerImpl extends AbstractSecurityManager {

  private static final String DEFAULT_SECURITY_AUTHORITY_PREFIX_SUFFIX = "_admin";
  @Getter(AccessLevel.PROTECTED)
  @Setter(AccessLevel.PROTECTED)
  private final String securityAuthorityPrefix;

  @Getter(AccessLevel.PROTECTED)
  @Setter(AccessLevel.PROTECTED)
  private final String i18nPrefix;

  @Getter(AccessLevel.PROTECTED)
  @Setter(AccessLevel.PROTECTED)
  private final Function<String, Boolean> hasAuthorityFn;

  public SecurityManagerImpl(
      Function<String, Boolean> hasAuthorityFn, String securityAuthorityPrefix, String i18nPrefix) {
    this.hasAuthorityFn = hasAuthorityFn;
    this.securityAuthorityPrefix = securityAuthorityPrefix;
    this.i18nPrefix = i18nPrefix;
  }

  public SecurityManagerImpl(Class entityClass, Function<String, Boolean> hasAuthorityFn) {
    this(hasAuthorityFn,
        CaseFormatUtils.convertUpperCamelToLowerUnderscore(entityClass.getSimpleName()) + DEFAULT_SECURITY_AUTHORITY_PREFIX_SUFFIX,
        entityClass.getName()
    );
  }

  public SecurityManagerImpl(Class entityClass, String entityClassSecurityAuthoritySuffix,
      Function<String, Boolean> hasAuthorityFn) {
    this(hasAuthorityFn,
        CaseFormatUtils.convertUpperCamelToLowerUnderscore(entityClass.getSimpleName())
            + entityClassSecurityAuthoritySuffix,
        entityClass.getName()
    );
  }

  @Override
  protected String getSecurityAuthorityPrefix() {
    return this.securityAuthorityPrefix;
  }

  @Override
  protected String getI18nPrefix() {
    return this.i18nPrefix;
  }

  @Override
  protected Function<String, Boolean> getHasAuthorityFn() {
    return this.hasAuthorityFn;
  }
}
